package com.example.springboot_demo.controller;

import com.example.springboot_demo.utils.AjaxResult;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

//redis测试
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {

    @Resource
    private RedisTemplate<String, Object>  redisTemplate;

      final String test_key= "test_set_scan";
    @PostConstruct
    public void initSet() {
        //新增 2w条数据，如果数据量较少，则会一次性的返回所有数据，比如之前是200
        Integer[] integers = new Integer[20000];
        for (int i = 0; i < 20000; i++) {
            integers[i]=i;
        }
        redisTemplate.opsForSet().add(test_key,integers);
        redisTemplate.expire(test_key,10,TimeUnit.MINUTES);
    }
    //测试加入数据
    @GetMapping("/testRedis")
    public AjaxResult testRedis(String key, Integer val) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key,val,120, TimeUnit.SECONDS);
        valueOperations.increment(key);

        Object obj = redisTemplate.opsForValue().get(key);

        //redisTemplate.opsForList().s

        return AjaxResult.success(obj);
    }

    /**
     * 测试set 集合的 扫描返回
     * 使用游标的方式返回 ：Cursor<Object> cursor = redisTemplate.opsForSet().scan(test_key, ScanOptions.scanOptions().match("*").count(maxResult).build());
     * 每次返回最多 maxResult 的数据，根据返回的游标值进行多次迭代，直到遍历当前所有的set数据
     * 游标功能主要通过 SCAN, SSCAN, HSCAN, 和 ZSCAN 命令提供，分别用于迭代 key 空间、set、hash 和 sorted set
     * set 集合 操作如下：SSCAN test_set_scan  0 COUNT 5
    */
    @GetMapping("/testSetScan")
    public AjaxResult testSetScan(Integer maxResult) {
        //initSet();
        Cursor<Object> cursor = redisTemplate
                .opsForSet()
                //返回以2开头的数据，每次返回100条进行处理
                .scan(test_key, ScanOptions.scanOptions().match("2*").count(maxResult).build());

        List<Integer> userIdList = new ArrayList<>();
        while (cursor.hasNext()) {
            Integer userId = (Integer) cursor.next();
            userIdList.add(userId);
        }


        return AjaxResult.success(userIdList);
    }
}
